/**
 * 缓存
 * @return {string} {格式化后的当前时间}
 */
export default class Storage {

  /**
   *
   * @param {string} driver
   */
  constructor(driver) {
    this.initDriver(driver);
  }

  /**
   * @param {'local'|'session'} driver
   * @return {undefined}
   * @throws {Error}
   */
  initDriver(driver) {
    switch (driver) {
      case 'local' :
        this.driver = localStorage;
        break;
      case 'session' :
        this.driver = sessionStorage;
        break;
      default :
        throw new Error('driver is not invalidate value in (local|session)');
    }
  }

  /**
   * @param {string} key
   * @param {*} value
   * @return {*}
   */
  cache(key, value) {
    if (! value) return this.get(key);

    this.set(key, value);
  }

  /**
   * @param key
   * @param value
   * @return {undefined}
   */
  set(key, value) {
    this.driver.setItem(key, JSON.stringify(value));
  }

  /**
   * @param key
   * @param {*} default_val
   * @return {*}
   */
  get(key, default_val = null) {
    let val = this.driver.getItem(key);

    if (val) return JSON.parse(val);

    return default_val;
  }
}